package com.example.service.impl;

import cn.undraw.util.ConvertUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.dto.CommentDTO;
import com.example.domain.entity.Comment;
import com.example.domain.entity.User;
import com.example.mapper.CommentMapper;
import com.example.service.CommentLikeService;
import com.example.service.CommentService;
import com.example.util.AuthUtils;
import com.example.util.page.PageInfo;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author readpage
 * @since 2023-02-03 16:15
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    private CommentMapper commentMapper;

    @Resource
    private CommentLikeService commentLikeService;


    @Override
    public Comment save(CommentDTO commentDTO) {
        // 模拟获取认证信息
        User user = AuthUtils.get();
        Comment comment = ConvertUtils.cloneDeep(commentDTO, Comment.class);
        comment.setUid(user.getId());
        comment.setAddress("来自上海");
        comment.setUser(user);
        // 添加评论
        if (commentMapper.insert(comment) < 1) {
            throw new RuntimeException();
        }
        return comment;
    }

    @Override
    public PageInfo<Comment> pageByAid(CommentDTO dto) {
        PageHelper.startPage(dto.getCurrent(), dto.getSize());
        // 根据文章id查询评论列表(不包含回复)
        List<Comment> list = commentMapper.selectListByAid(dto.getArticleId());
        // 添加评论对应的回复
        for (int i = 0; i < list.size(); i++) {
            Comment comment = list.get(i);
            Long id = comment.getId();
            // 合并redis中的点赞数量
            comment.setLikes(comment.getLikes() + commentLikeService.getLikeCount(id));
            // 分页查询回复
            PageInfo<Comment> replyPage = replyPageByPid(new CommentDTO(1, 5, id));
            Comment.Reply reply = new Comment.Reply();
            // 拷贝
            reply = ConvertUtils.cloneDeep(replyPage, Comment.Reply.class);
            comment.setReply(reply);
        }

        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Comment> replyPageByPid(CommentDTO dto) {
        PageHelper.startPage(dto.getCurrent(), dto.getSize());
        // 通过parentId查询回复列表
        List<Comment> list = commentMapper.selectListByPid(dto.getParentId());
        for (Comment reply : list) {
            Long id = reply.getId();
            // 合并redis中的点赞数量
            reply.setLikes(reply.getLikes() + commentLikeService.getLikeCount(id));
        }
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<List<Comment>> page(int pageNum, int pageSize) {
        return null;
    }

    @Override
    public boolean updateBatchById(List<Comment> list) {
        return commentMapper.updateBatchById(list) > 0;
    }

}
